import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import Layout from '../views/Layout.vue'
import Home from '../views/Home.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login,
      meta: { title: '登录' }
    },
    {
      path: '/register',
      name: 'register',
      component: Register,
      meta: { title: '注册' }
    },
    {
      path: '/',
      component: Layout,
      redirect: '/home',
      children: [
        {
          path: 'home',
          name: 'home',
          component: Home,
          meta: { title: '首页' }
        },
        {
          path: 'article',
          name: 'article',
          component: () => import('../views/Article.vue'),
          meta: { title: '文章管理' }
        },
        {
          path: 'category',
          name: 'category',
          component: () => import('../views/Category.vue'),
          meta: { title: '分类管理' }
        },
        {
          path: 'user',
          name: 'user',
          component: () => import('../views/User.vue'),
          meta: { title: '个人中心' }
        }
      ]
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 大事件管理系统` : '大事件管理系统'
  
  // 如果访问的不是登录页和注册页，检查是否有token
  if (to.path !== '/login' && to.path !== '/register') {
    const token = localStorage.getItem('token')
    if (!token) {
      next('/login')
      return
    }
  }
  next()
})

export default router 